import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  clearHistoriesAction,
  clearSuggestsAction,
  getSuggestsAction,
  saveHistoriesAction,
} from '@/store/action/search';
import { setLocalHistories } from '@/utils/storage';
import { Toast } from 'antd-mobile';
import Dompurify from 'dompurify';
import React, { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styles from './index.module.scss';

const lighHight = (str: string, keyword: string) => {
  const reg = new RegExp(`(${keyword})`, 'gi');
  return str.replace(reg, '<span onclick="alert(12)">$1</span>');
};

export default function Search() {
  const dispatch = useDispatch();
  const history = useHistory();

  const timerIdRef = useRef(0);
  const [keyword, setKeyword] = useState('');
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.trim();
    setKeyword(value);
    clearTimeout(timerIdRef.current);
    if (!value) return;

    timerIdRef.current = window.setTimeout(() => {
      dispatch(getSuggestsAction(value));
    }, 500);
  };
  const { suggests, histories } = useAppSelector((state) => state.search);

  useEffect(() => {
    return () => {
      dispatch(clearSuggestsAction());
    };
  }, [dispatch]);

  useEffect(() => {
    setLocalHistories(histories);
  }, [histories]);

  const handleSearch = () => {
    if (!keyword) return Toast.show({ content: '搜索内容不能为空' });

    dispatch(saveHistoriesAction(keyword));
    history.push({
      pathname: '/search/result',
      search: `q=${keyword}`,
    });
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  const handleClearSuggests = () => {
    setKeyword('');
  };

  useEffect(() => {
    if (!keyword) dispatch(clearSuggestsAction());
  }, [keyword, dispatch]);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span className="search-text" onClick={handleSearch}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              placeholder="请输入关键字搜索"
              onChange={handleChange}
              value={keyword}
              onKeyDown={handleKeyDown}
            />

            {/* 清空输入框按钮 */}
            <Icon type="iconbtn_tag_close" className="icon-close" onClick={handleClearSuggests} />
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      {!keyword ? (
        <div className="history" style={{ display: 'block' }}>
          {!!histories.length && (
            <div className="history-header">
              <span>搜索历史</span>
              <span onClick={() => dispatch(clearHistoriesAction())}>
                <Icon type="iconbtn_del" />
              </span>
            </div>
          )}

          <div className="history-list">
            {histories.map((item) => {
              return (
                <span className="history-item" key={item}>
                  {item}
                  <span className="divider"></span>
                </span>
              );
            })}
          </div>
        </div>
      ) : (
        <div className="search-result">
          {suggests.map((item, index) => {
            return (
              <div className="result-item" key={index}>
                <Icon className="icon-search" type="iconbtn_search" />
                <div
                  className="result-value"
                  dangerouslySetInnerHTML={{
                    __html: Dompurify.sanitize(lighHight(item, keyword)),
                  }}
                ></div>
              </div>
            );
          })}
        </div>
      )}

      {/* 搜素建议结果列表 */}
    </div>
  );
}
